package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.adapter.CheckedCarItemAdapter;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.utils.AliYunUtils;
import com.bjesc_b2c.app.appraiset.utils.BitmapUtil;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.utils.GralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.RxGralleryFinalUtils;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.popupwindow.SelectPhotoPop;
import com.google.gson.Gson;
import com.rxretrofit_build.CarPhotoID;
import com.rxretrofit_build.model.RxBusBean;
import com.rxretrofit_build.util.MapUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import app.pinggushi.bjesc.com.baserecyclerview.adapter.MultiItemTypeAdapter;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageRadioResultEvent;
import master_bean.CheckedCarItemBean;
import master_bean.SinglePhotoUpBean;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

import static android.view.View.GONE;

/**
 * Created by lenovo on 2017/2/25.
 * 装置-发动机、变速箱跳进来的
 */

public class ComplexComponentsDetailActivity extends BaseActivity implements MultiItemTypeAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener {
    @InjectView(R.id.tv_title)
    TextView titleTv;
    @InjectView(R.id.edit_detail)
    EditText detailEdit;

    @InjectView(R.id.rlty_light)
    RelativeLayout lightRlty;
    @InjectView(R.id.rlty_moderate)
    RelativeLayout moderateRlty;
    @InjectView(R.id.rlty_seriously)
    RelativeLayout seriouslyRlty;

    @InjectView(R.id.recycler_itemdetail_photo)
    RecyclerView photoRecycler;
    @InjectView(R.id.cb_light_one)
    CheckBox lightOneCb;
    @InjectView(R.id.cb_light_two)
    CheckBox lightTwoCb;
    @InjectView(R.id.cb_light_three)
    CheckBox lightThreeCb;
    @InjectView(R.id.cb_light_four)
    CheckBox lightFourCb;
    @InjectView(R.id.cb_light_five)
    CheckBox lightFiveCb;
    @InjectView(R.id.cb_moderate_one)
    CheckBox moderateOneCb;
    @InjectView(R.id.cb_moderate_two)
    CheckBox moderateTwoCb;
    @InjectView(R.id.cb_moderate_three)
    CheckBox moderateThreeCb;
    @InjectView(R.id.cb_moderate_four)
    CheckBox moderateFourCb;
    @InjectView(R.id.cb_moderate_five)
    CheckBox moderateFiveCb;
    @InjectView(R.id.cb_seriously_one)
    CheckBox seriouslyOneCb;
    @InjectView(R.id.cb_seriously_two)
    CheckBox seriouslyTwoCb;
    @InjectView(R.id.cb_seriously_three)
    CheckBox seriouslyThreeCb;


    private List<String> lightList;
    private List<String> moderateList;
    private List<String> seriouslyList;

    private CheckedCarItemAdapter itemAdapter;
    private List<CheckedCarItemBean> photoBeanList;
    private SelectPhotoPop photoPop;
    private int currentIndex;
    private String sourceID;
    private List<String> fileList;   //阿里文件名
    private boolean isSave;
    private SinglePhotoUpBean.Option.DandG DG;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complex_components);
        ButterKnife.inject(this);
        initTitle();
        getData();
    }

    private void getData() {
        HashMap<String, Object> build = new MapUtil()
                .put("id", CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()))
                .put("class_id", CarPhotoID.deviceID)
                .put("attr_id", sourceID)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).getSinglePhoto()
                , new BaseSubscriber<TokenBean<SinglePhotoUpBean>>(this) {
                    @Override
                    public void onSuccess(TokenBean<SinglePhotoUpBean> o) {
                        if (o.getStatus_code() == 9) {
                            isSave = false;
                        } else if (o.getStatus_code() == 0) {
                            isSave = true;
                        }
                        getItemList(o.getData());
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }


    private void getItemList(SinglePhotoUpBean data) {
        photoBeanList = new ArrayList<>();
        fileList = new ArrayList<>();
        if (data != null ) {
            if(data.getImg_info() != null && data.getImg_info().size() > 0){
                for (int i = 0; i < data.getImg_info().size(); i++) {
                fileList.add(TimeListUilts.subUrl(data.getImg_info().get(i))); //将文件名添加到集合，以后需要用来删除的
                photoBeanList.add(new CheckedCarItemBean(data.getImg_info().get(i), false));
                //如果以后显示多张，这里需要判断最后一个，然后设置true
            }
        }else{
            photoBeanList.add(new CheckedCarItemBean("", false));
        }
        if (!TextUtils.isEmpty(data.getDescription())) {
                detailEdit.setText(data.getDescription());
            }
            if (data.getOption() != null) {

                if (data.getOption().getD() != null) {

                    DG = data.getOption().getD();
                } else {
                    DG = data.getOption().getG();
                }
                if (DG != null) {
                    setCheckBoxStatus(DG);
                } else {
                    DG = new SinglePhotoUpBean.Option.DandG();
                }
            } else {
                DG = new SinglePhotoUpBean.Option.DandG();
            }
        } else {
            photoBeanList.add(new CheckedCarItemBean("", false));
            DG = new SinglePhotoUpBean.Option.DandG();
        }
        initViews();
    }

    /**
     * 设置多选的状态
     *
     * @param DG
     */
    private void setCheckBoxStatus(SinglePhotoUpBean.Option.DandG DG) {
        if (!TextUtils.isEmpty(DG.getLightOne())) {
            lightOneCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getLightTwo())) {
            lightTwoCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getLightThree())) {
            lightThreeCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getLightFour())) {
            lightFourCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getLightFive())) {
            lightFiveCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getModerateOne())) {
            moderateOneCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getModerateTwo())) {
            moderateTwoCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getModerateThree())) {
            moderateThreeCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getModerateFour())) {
            moderateFourCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getModerateFive())) {
            moderateFiveCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getSeriouslyOne())) {
            seriouslyOneCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getSeriouslyTwo())) {
            seriouslyTwoCb.setChecked(true);
        }
        if (!TextUtils.isEmpty(DG.getSeriouslyThree())) {
            seriouslyThreeCb.setChecked(true);
        }
    }

    private void initViews() {
        photoPop = new SelectPhotoPop(this, popListener);
        photoRecycler.setLayoutManager(new GridLayoutManager(this, 3, LinearLayoutManager.VERTICAL, false));
        itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, photoBeanList);
        photoRecycler.setAdapter(itemAdapter);
        itemAdapter.setOnItemClickListener(this);
    }

    private void initTitle() {
        lightList = getIntent().getStringArrayListExtra("light");
        moderateList = getIntent().getStringArrayListExtra("moderate");
        seriouslyList = getIntent().getStringArrayListExtra("seriously");
        sourceID = getIntent().getStringExtra("sourceID");

        if (!TextUtils.isEmpty(getIntent().getStringExtra("title"))) {
            titleTv.setText(getIntent().getStringExtra("title"));
        }

        if (lightList != null && lightList.size() > 0) {
            lightRlty.setVisibility(View.VISIBLE);
            setCheckBoxTest(lightOneCb, lightTwoCb, lightThreeCb, lightFourCb, lightFiveCb, lightList);
        } else {
            lightRlty.setVisibility(GONE);
        }

        if (moderateList != null && moderateList.size() > 0) {
            moderateRlty.setVisibility(View.VISIBLE);
            setCheckBoxTest(moderateOneCb, moderateTwoCb, moderateThreeCb, moderateFourCb, moderateFiveCb, moderateList);
        } else {
            moderateRlty.setVisibility(GONE);
        }

        if (seriouslyList != null && seriouslyList.size() > 0) {
            seriouslyRlty.setVisibility(View.VISIBLE);
            setCheckBoxTest(seriouslyOneCb, seriouslyTwoCb, seriouslyThreeCb, null, null, seriouslyList);
        } else {
            seriouslyRlty.setVisibility(GONE);
        }

        lightOneCb.setOnCheckedChangeListener(this);
        lightTwoCb.setOnCheckedChangeListener(this);
        lightThreeCb.setOnCheckedChangeListener(this);
        lightFourCb.setOnCheckedChangeListener(this);
        lightFiveCb.setOnCheckedChangeListener(this);
        moderateOneCb.setOnCheckedChangeListener(this);
        moderateTwoCb.setOnCheckedChangeListener(this);
        moderateThreeCb.setOnCheckedChangeListener(this);
        moderateFourCb.setOnCheckedChangeListener(this);
        moderateFiveCb.setOnCheckedChangeListener(this);
        seriouslyOneCb.setOnCheckedChangeListener(this);
        seriouslyTwoCb.setOnCheckedChangeListener(this);
        seriouslyThreeCb.setOnCheckedChangeListener(this);

        if (sourceID.equals(CarPhotoID.CarDeviceID.gearbox)) {   //变速箱
            lightThreeCb.setVisibility(GONE);
            lightFourCb.setVisibility(GONE);
            lightFiveCb.setVisibility(GONE);
            moderateThreeCb.setVisibility(GONE);
            moderateFourCb.setVisibility(GONE);
            moderateFiveCb.setVisibility(GONE);
            seriouslyThreeCb.setVisibility(GONE);
        }
    }

    /**
     * 设置CheckBox的文本
     *
     * @param one
     * @param two
     * @param three
     * @param four
     * @param five
     * @param list
     */
    private void setCheckBoxTest(CheckBox one, CheckBox two, CheckBox three, CheckBox four, CheckBox five, List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            switch (i) {
                case 0:
                    one.setText(list.get(i));
                    break;
                case 1:
                    two.setText(list.get(i));
                    break;
                case 2:
                    three.setText(list.get(i));
                    break;
                case 3:
                    if (four != null) {
                        four.setText(list.get(i));
                    }
                    break;
                case 4:
                    if (five != null) {
                        five.setText(list.get(i));
                    }
                    break;
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.cb_light_one:
                if (b) {
                    DG.setLightOne("1");
                } else {
                    DG.setLightOne("");
                }
                break;
            case R.id.cb_light_two:
                if (b) {
                    DG.setLightTwo("1");
                } else {
                    DG.setLightTwo("");
                }
                break;
            case R.id.cb_light_three:
                if (b) {
                    DG.setLightThree("1");
                } else {
                    DG.setLightThree("");
                }
                break;
            case R.id.cb_light_four:
                if (b) {
                    DG.setLightFour("1");
                } else {
                    DG.setLightFour("");
                }
                break;
            case R.id.cb_light_five:
                if (b) {
                    DG.setLightFive("1");
                } else {
                    DG.setLightFive("");
                }
                break;
            case R.id.cb_moderate_one:
                if (b) {
                    DG.setModerateOne("1");
                } else {
                    DG.setModerateOne("");
                }
                break;
            case R.id.cb_moderate_two:
                if (b) {
                    DG.setModerateTwo("1");
                } else {
                    DG.setModerateTwo("");
                }
                break;
            case R.id.cb_moderate_three:
                if (b) {
                    DG.setModerateThree("1");
                } else {
                    DG.setModerateThree("");
                }
                break;
            case R.id.cb_moderate_four:
                if (b) {
                    DG.setModerateFour("1");
                } else {
                    DG.setModerateFour("");
                }
                break;
            case R.id.cb_moderate_five:
                if (b) {
                    DG.setModerateFive("1");
                } else {
                    DG.setModerateFive("");
                }
                break;
            case R.id.cb_seriously_one:
                if (b) {
                    DG.setSeriouslyOne("1");
                } else {
                    DG.setSeriouslyOne("");
                }
                break;
            case R.id.cb_seriously_two:
                if (b) {
                    DG.setSeriouslyTwo("1");
                } else {
                    DG.setSeriouslyTwo("");
                }
                break;
            case R.id.cb_seriously_three:
                if (b) {
                    DG.setSeriouslyThree("1");
                } else {
                    DG.setSeriouslyThree("");
                }
                break;

        }
    }

    private View.OnClickListener popListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.rlty_select_camera:     //选择相机
                    GralleryFinalUtils.openCamera(gralleryCallBack);
                    break;
                case R.id.rlty_select_album:    //选择相册
                    RxGralleryFinalUtils.openRadioImage(ComplexComponentsDetailActivity.this, rxGalleryCallBack);
                    break;
            }
            if (photoPop.isShowing()) {
                photoPop.dismiss();
            }
        }
    };

    private RxGralleryFinalUtils.RxGalleryFinalCallBack rxGalleryCallBack = new RxGralleryFinalUtils.RxGalleryFinalCallBack() {
        @Override
        public void onEvent(ImageRadioResultEvent imageRadioResultEvent) {
            Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(imageRadioResultEvent.getResult().getOriginalPath());
            Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
            BitmapUtil.saveBitmapToLocal(sbitmap1,imageRadioResultEvent.getResult().getOriginalPath());
            refreshImage(imageRadioResultEvent.getResult().getOriginalPath(), currentIndex);
        }
    };

    private GalleryFinal.OnHanlderResultCallback gralleryCallBack = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (reqeustCode == GralleryFinalUtils.CAMERA) {
                Bitmap bitmap = BitmapUtil.getBitmapFromSDCard(resultList.get(0).getPhotoPath());
                Bitmap sbitmap1 = BitmapUtil.storeImage(bitmap,900,1200);
                BitmapUtil.saveBitmapToLocal(sbitmap1,resultList.get(0).getPhotoPath());
                refreshImage(resultList.get(0).getPhotoPath(), currentIndex);
            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };

    protected void refreshImage(String url, int index) {
        photoBeanList.set(index, new CheckedCarItemBean(url, true));
        itemAdapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        currentIndex = position;
        if (TextUtils.isEmpty(photoBeanList.get(currentIndex).getPhoto())) {
            //跳转相机
            photoPop.showAtLocation(this.findViewById(R.id.llty_root), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        } else {
            //跳转大图
            Intent bigIntent = new Intent(ComplexComponentsDetailActivity.this, BigCarSourcePhotoActivity.class);
            bigIntent.putExtra("classId", CarPhotoID.deviceID);
            bigIntent.putExtra("sourceId", sourceID);
            bigIntent.putExtra("photoUrl", photoBeanList.get(position).getPhoto());
            if (fileList != null && fileList.size() > 0) {
                bigIntent.putExtra("fileName",TimeListUilts.subUrl(photoBeanList.get(position).getPhoto()));
            }
            bigIntent.putExtra("isSave", isSave);
            startIntent(bigIntent, 26);
        }
    }

    @Override
    protected void doOnNext(RxBusBean rxBusBean) {
        super.doOnNext(rxBusBean);
        if (rxBusBean.getRequestMark().equals(sourceID)) {
            if (!TextUtils.isEmpty(photoBeanList.get(currentIndex).getPhoto())) {
                photoBeanList.set(currentIndex, new CheckedCarItemBean("", false));
            }
            itemAdapter = new CheckedCarItemAdapter(this, R.layout.layout_item_car_surface_item_detail, photoBeanList);
            itemAdapter.setOnItemClickListener(this);
            photoRecycler.setAdapter(itemAdapter);
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }


    @OnClick({R.id.rl_return, R.id.tv_save_info, R.id.tv_reset})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_return:
                onBackPressed();
                break;
            case R.id.tv_save_info:
                saveImg();
                break;
            case R.id.tv_reset:
                reset();
                break;
        }
    }

    private void reset() {
        DG = new SinglePhotoUpBean.Option.DandG();
        lightOneCb.setChecked(false);
        lightTwoCb.setChecked(false);
        lightThreeCb.setChecked(false);
        lightFourCb.setChecked(false);
        lightFiveCb.setChecked(false);
        moderateOneCb.setChecked(false);
        moderateTwoCb.setChecked(false);
        moderateThreeCb.setChecked(false);
        moderateFourCb.setChecked(false);
        moderateFiveCb.setChecked(false);
        seriouslyOneCb.setChecked(false);
        seriouslyTwoCb.setChecked(false);
        seriouslyThreeCb.setChecked(false);
    }


    private void saveImg() {
        SinglePhotoUpBean bean = new SinglePhotoUpBean();
        bean.setImg_info(getUpLoadImgList());
        bean.setAttr_id(sourceID);
        bean.setDescription(detailEdit.getText().toString());
        bean.setOption(getOption());
        bean.setId(CustomSharedPreferences.getString(this, KeyBean.CARID.valueOf(), KeyBean.FILE_NAME.valueOf()));
        HashMap<String, Object> build = new MapUtil()
                .put("data", new Gson().toJson(bean))
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(this, build).create(IApiActivityRequest.class).saveDevice()
                , new BaseSubscriber<TokenBean>(this) {
                    @Override
                    public void onSuccess(TokenBean o) {
                        Intent intent = new Intent();
                        intent.putExtra("sourceID", sourceID);
                        intent.putExtra("isChange", true);
                        setResult(0, intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        if (!isSave) {
            intent.putExtra("sourceID", sourceID);
            intent.putExtra("isChange", false);
        }
        setResult(0, intent);
        finish();
    }

    /**
     * 设置选项
     *
     * @return
     */
    private SinglePhotoUpBean.Option getOption() {
        SinglePhotoUpBean.Option option = new SinglePhotoUpBean.Option();
        if (sourceID.equals(CarPhotoID.CarDeviceID.engine)) {     //发动机
            option.setG(setG(DG));
        } else if (sourceID.equals(CarPhotoID.CarDeviceID.gearbox)) {   //变速箱
            option.setD(setD(DG));
        }
        return option;
    }

    private SinglePhotoUpBean.Option.D setD(SinglePhotoUpBean.Option.DandG dg) {
        master_bean.SinglePhotoUpBean.Option.D d = new SinglePhotoUpBean.Option.D();
        d.setLightOne(dg.getLightOne());
        d.setLightTwo(dg.getLightTwo());
        d.setLightThree(dg.getLightThree());
        d.setLightFour(dg.getLightFour());
        d.setLightFive(dg.getLightFive());
        d.setModerateOne(dg.getModerateOne());
        d.setModerateTwo(dg.getModerateTwo());
        d.setModerateThree(dg.getModerateThree());
        d.setModerateFour(dg.getModerateFour());
        d.setModerateFive(dg.getModerateFive());
        d.setSeriouslyOne(dg.getSeriouslyOne());
        d.setSeriouslyTwo(dg.getSeriouslyTwo());
        d.setSeriouslyThree(dg.getSeriouslyThree());
        return d;
    }

    private SinglePhotoUpBean.Option.G setG(SinglePhotoUpBean.Option.DandG dg) {
        master_bean.SinglePhotoUpBean.Option.G g = new SinglePhotoUpBean.Option.G();
        g.setLightOne(dg.getLightOne());
        g.setLightTwo(dg.getLightTwo());
        g.setLightThree(dg.getLightThree());
        g.setLightFour(dg.getLightFour());
        g.setLightFive(dg.getLightFive());
        g.setModerateOne(dg.getModerateOne());
        g.setModerateTwo(dg.getModerateTwo());
        g.setModerateThree(dg.getModerateThree());
        g.setModerateFour(dg.getModerateFour());
        g.setModerateFive(dg.getModerateFive());
        g.setSeriouslyOne(dg.getSeriouslyOne());
        g.setSeriouslyTwo(dg.getSeriouslyTwo());
        g.setSeriouslyThree(dg.getSeriouslyThree());
        return g;
    }

    /**
     * 将图片存到一个集合里面准备上传,并且提交到阿里云
     *
     * @return
     */
    private List<String> getUpLoadImgList() {
        List<String> photoList = new ArrayList<>();
        for (int i = 0; i < photoBeanList.size(); i++) {    //循环上传图片到阿里
            if (!TextUtils.isEmpty(photoBeanList.get(i).getPhoto())) {
                if (!photoBeanList.get(i).getPhoto().contains("http")) {
                    String fileName = TimeListUilts.getObjectKey() + ".png";
                    AliYunUtils.aLiYunUpLoadFuncation(
                            this,
                            sourceID,       //图片ID
                            fileName,                           //图片名
                            photoBeanList.get(i).getPhoto()     //图片路径
                            , null);

                    photoList.add(fileName);
                } else {
                    photoList.add(TimeListUilts.subUrl(photoBeanList.get(i).getPhoto()));
                }
            }
        }
        return photoList;
    }

}
